package cn.skylark.wcm.controller;

import cn.skylark.wcm.common.util.ReturnMap;
import cn.skylark.wcm.entity.Resources;
import cn.skylark.wcm.service.ResourcesService;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 资源页面控制器
 *
 * @author chuhl
 * @since 2017年12月4日14:14:18
 */
@RestController
@RequestMapping("/resources")
public class ResourcesController {
    private Logger logger = LoggerFactory.getLogger(ResourcesController.class);
    @Autowired
    ResourcesService resourcesService;

    /**
     * 资源数据取得
     *
     * @param resources Resources
     * @param draw      String
     * @param start     int
     * @param length    int
     * @return Map<String   , Object>
     */
    @RequestMapping
    public Map<String, Object> getAll(Resources resources, String draw,
                                      @RequestParam(required = false, defaultValue = "1") int start,
                                      @RequestParam(required = false, defaultValue = "10") int length) {
        Map<String, Object> map = new HashMap<>();
        PageInfo<Resources> pageInfo = resourcesService.selectByPage(resources, start, length);
        map.put("draw", draw);
        map.put("recordsTotal", pageInfo.getTotal());
        map.put("recordsFiltered", pageInfo.getTotal());
        map.put("data", pageInfo.getList());
        return map;
    }

    /**
     * 取得指定权限
     *
     * @param rid Integer 权限id
     * @return List<Resources>
     */
    @RequestMapping("/resourcesWithSelected")
    public List<Resources> resourcesWithSelected(Integer rid) {
        return resourcesService.queryResourcesListWithSelected(rid);
    }

    /**
     * 资源追加
     * 业务：通过所添加的信息中权限名称字段，判断是否存在该权限，如果存在则返回flg=1和提示信息
     * 如果不存在就进行添加操作，成功返回flg=0和提示信息，出现异常则返回flg=2和提示信息，
     * 此功能只是用于我们的超级管理员
     *
     * @param resources Resources
     * @return String
     */
    @CacheEvict(cacheNames = "resources", allEntries = true)
    @RequestMapping(value = "/add")
    public String add(Resources resources) {
        logger.info("传入参数=========" + resources);
        ReturnMap returnMap = new ReturnMap();
        Resources r = resourcesService.selectByName(resources);
        if (r != null) {
            returnMap.setFlg(1);
            returnMap.setMessage("该权限已存在！");
            return returnMap.ReturnMap();
        }
        try {
            resourcesService.save(resources);
            // 更新权限
            returnMap.setMessage("添加权限成功");
            returnMap.setFlg(0);
        } catch (Exception e) {
            logger.info("异常类型为====" + e);
            e.printStackTrace();
            returnMap.setMessage("添加权限失败");
            returnMap.setFlg(2);
        }
        return returnMap.ReturnMap();
    }

    /**
     * 逻辑删除权限
     * 业务：通过用户id，确定每个用户下面的角色，然后更新角色和权限关联表，逻辑删除
     * 每个角色下面的该权限。
     *
     * @param userid      租户id
     * @param resourcesid 权限id
     * @return
     */
    @RequestMapping(value = "/logicDelete")
    public String logicDelete(Integer userid, String[] resourcesid) {
        logger.info("传入参数" + "userid====" + userid + "resourcesid=========" + resourcesid);
        ReturnMap returnMap = new ReturnMap();
        try {
            resourcesService.deleteResourceById(userid, resourcesid);
            returnMap.setFlg(0);
            returnMap.setMessage("删除成功");
        } catch (Exception e) {
            logger.info("异常类型为====" + e);
            e.printStackTrace();
            returnMap.setFlg(1);
            returnMap.setMessage("删除失败");
        }
        return returnMap.ReturnMap();

    }

    /**
     * 根据用户id 获取用户权限列表
     *
     * @param userid 用户id
     * @param start  开始是第几条
     * @param length 每页多少条
     * @return
     */
    @RequestMapping(value = "/getResourcesListByUserid")
    public Map<String, Object> getResourcesListByUserid(Integer userid, HttpServletRequest request,
                                                        @RequestParam(required = false, defaultValue = "1") int start,
                                                        @RequestParam(required = false, defaultValue = "10") int length) {
        logger.info("传入参数==== userid： " + userid);
        String searchValue = request.getParameter("search[value]");
        logger.info("search:" + searchValue);
        String flag = request.getParameter("flag");
        Map<String, Object> map = new HashMap<>();
        try {
            //通过租户id获取该租户下的所有权限
            PageInfo<Resources> pageInfo = resourcesService.getResourcesListByUserid(userid,flag, start, length, searchValue);
            map.put("recordsTotal", pageInfo.getTotal());
            map.put("recordsFiltered", pageInfo.getTotal());
            map.put("data", pageInfo.getList());
            map.put("flg", 0);
            map.put("message", "获取权限列表成功");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("flg", 2);
            map.put("message", "获取权限列表失败");
        }
        return map;
    }
}
